<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: chenqinglin
 * Date: 17-8-7
 * Time: 下午3:44
 */
require_once(APPPATH."third_party/qiniusdk/autoload.php");
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;


function saveUrl($url){
    log_message('error','saveUrl');
    $bucket = 'lebang';
    $directory = date('Ymd/');
    $unknown_extension = 'unk';

    $CI = &get_instance();
    $qiniu_conf =$CI->config->item('qiniu');
    $accessKey = $qiniu_conf['access_key'];
    $secretKey = $qiniu_conf['secret_key'];

    // 初始化签权对象
    $auth = new Auth($accessKey, $secretKey);
    // 生成上传Token
    $token = $auth->uploadToken($bucket);
    // 构建 UploadManager 对象
    $uploadMgr = new UploadManager();
    //初始化BucketManager
    $bucketMgr = new BucketManager($auth);

    $extension = pathinfo($url, PATHINFO_EXTENSION) ? : $unknown_extension;
    $dstPath = sprintf('%s%s.%s',$directory,random(40),$extension);
    //log_message('error','saveUrl dstpath '.$dstPath);
    list($ret, $err) = $bucketMgr->fetch($url, $bucket, ltrim($dstPath, '/'));
    return $err === null ? $dstPath : false;
}

function random($length = 16)
{
    $string = '';

    while (($len = strlen($string)) < $length) {
        $size = $length - $len;

        $bytes = random_bytes($size);

        $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
    }

    return $string;
}
?>